<template>
    <div class="app-container">
        <div class="mb20 flex-space-between">
            <div style="width: 100%">
                <el-input v-model="filters.name" prefix-icon="search"
                          :placeholder="$t('common.search')" clearable
                          style="width: 36%"></el-input>
                <el-select v-model="filters.tag" class="ml10"
                           :placeholder="$t('datasource.tag')" multiple
                           clearable
                           max-collapse-tags="2" collapse-tags
                           style="width: 20%">
                    <el-option v-for="tag in tags" :value="tag" :label="tag"
                               :key="tag"></el-option>
                </el-select>
                <el-button @click="openAddDatasourceDialog" class="ml10"
                           icon="plus">{{ $t('datasource.addDatasource') }}
                </el-button>
            </div>
            <div class="flex-center">
                <el-icon size="20" class="ml20">
                    <a href="https://gitee.com/xgpxg/db-diff" target="_blank">
                        <svg-icon icon-class="gitee"></svg-icon>
                    </a>
                </el-icon>
                <el-icon size="20" class="ml20">
                    <svg-icon icon-class="github"></svg-icon>
                </el-icon>
                <switch-language></switch-language>
            </div>
        </div>
        <el-row :gutter="10">
            <el-col :span="6" :xl="6" :lg="8" :md="12" :sm="24" :xs="24"
                    v-for="ds in filterList" class="mb10">
                <el-card style="height: 250px">
                    <div class="fr fill-width" style="position:relative;">
                        <el-icon class="fr" size="30"
                                 style="position: absolute; right: 0">
                            <svg-icon :icon-class="ds.type"></svg-icon>
                        </el-icon>
                    </div>
                    <el-descriptions column="1">
                        <el-descriptions-item :label="$t('datasource.name')">
                            {{ ds.name }}（{{ ds.database }}）
                        </el-descriptions-item>
                        <el-descriptions-item :label="$t('datasource.tag')">
                            <template v-if="ds.tags">
                                <el-tag v-for="tag in (ds.tags || '').split(',')"
                                        type="info" class="ml5">
                                    {{ tag }}
                                </el-tag>
                            </template>
                            <template v-else>
                                -
                            </template>
                        </el-descriptions-item>
                        <el-descriptions-item
                                :label="$t('datasource.tableCount')">
                            {{ ds.tableCount ? ds.tableCount : '未知' }}
                        </el-descriptions-item>
                        <el-descriptions-item
                                :label="$t('datasource.syncTime')">
                            {{ ds.lastSyncTime ? ds.lastSyncTime : '-' }}
                        </el-descriptions-item>
                        <el-descriptions-item
                                :label="$t('datasource.compareTime')">
                            {{ ds.createDate ? ds.lastCompareTime : '-' }}
                        </el-descriptions-item>
                    </el-descriptions>
                    <el-button @click="showDatasourceDetail(ds)"
                               size="small" type="" icon="document">
                        {{ $t('button.detail') }}
                    </el-button>
                    <el-button size="small" @click="sync(ds)"
                               icon="refresh" :disabled="ds.syncing">
                        <span v-if="ds.syncing">
                            {{ $t('button.syncing') }}
                        </span>
                        <span v-else>
                          {{ $t('button.sync') }}
                        </span>
                    </el-button>
                    <el-button @click="select(ds)" size="small" type="primary"
                               icon="plus">
                        {{ $t('button.compare') }}
                    </el-button>
                    <span class="fr">
                       <el-button @click="edit(ds)" size="small" type=""
                                  icon="edit">
                       </el-button>
                       <el-button @click="remove(ds)" size="small" type=""
                                  icon="delete">
                       </el-button>
                   </span>
                </el-card>
                <div v-if="ds.selected" class="selected-parent">
                    <div class="selected flex-column-v">
                        <el-button @click="cancelSelected(ds)" type="primary">
                            {{ $t('button.cancel') }}
                        </el-button>
                        <span class="color-white mt10"
                              v-if="selected && selected.length===1">
                             {{ $t('datasource.choseTip') }}
                        </span>
                    </div>
                </div>
            </el-col>
            <el-col :span="6" :xl="4" :lg="8" :md="12" :sm="24" :xs="24"
                    class="mb10">
                <el-button @click="openAddDatasourceDialog" text
                           style="height: 250px"
                           class="fill-width">
                    <el-icon size="30">
                        <svg-icon icon-class="datasource"></svg-icon>
                    </el-icon>
                    <span style="font-size: 25px;margin-left: 10px;">
                        {{ $t('datasource.addDatasource') }}
                    </span>
                </el-button>
            </el-col>

        </el-row>
        <el-dialog :title="$t('datasource.readyCompare')"
                   v-model="showDiffDialog" width="40%"
                   draggable @closed="cleanSelected" destroy-on-close>
            <el-row class="">
                <el-col :span="10">
                    <el-card>
                        <div style="font-size: 20px" class="flex-column-v">
                            {{ selected[0].name }}
                        </div>
                        <div class="flex-column-v">
                            {{ selected[0].database }}
                        </div>
                        <div class="flex-column-v mt10">
                            <el-tag v-if="selected[0].tags"
                                    v-for="tag in (selected[0].tags || '').split(',')">
                                {{ tag }}
                            </el-tag>
                            <template v-else>
                                &nbsp;
                            </template>
                        </div>
                    </el-card>
                </el-col>
                <el-col :span="4">
                    <div style="margin-top: 50px" class="flex-column-v">
                        <svg-icon icon-class="vs" size="30"></svg-icon>
                    </div>
                </el-col>
                <el-col :span="10">
                    <el-card>
                        <div style="font-size: 20px" class="flex-column-v">
                            {{ selected[1].name }}
                        </div>
                        <div class="flex-column-v">
                            {{ selected[1].database }}
                        </div>
                        <div class="flex-column-v mt10">
                            <el-tag v-if="selected[1].tags"
                                    v-for="tag in (selected[1].tags || '').split(',')">
                                {{ tag }}
                            </el-tag>
                            <template v-else>
                                &nbsp;
                            </template>
                        </div>
                    </el-card>
                </el-col>
            </el-row>
            <el-button @click="goDiff" type="primary"
                       class="fill-width mt20 mb20">
                {{ $t('datasource.startCompare') }}
            </el-button>
        </el-dialog>
        <el-dialog :title="datasourceDialogTitle"
                   v-model="showAddDatasourceDialog"
                   width="500px" draggable
                   @close="resetTestConnection">
            <el-form ref="form" :model="form" :rules="rules" label-width="90"
                     label-position="left">
                <el-form-item :label="$t('datasource.type')" prop="type">
                    <el-select v-model="form.type" class="fill-width"
                               :placeholder="$t('datasource.placeholder.type')">
                        <el-option v-for="type in datasourceTypes"
                                   :value="type"
                                   :key="type">
                            {{ type }}
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item :label="$t('datasource.datasourceName')"
                              prop="name">
                    <el-input v-model="form.name"
                              :placeholder="$t('datasource.placeholder.datasourceName')"></el-input>
                </el-form-item>

                <el-form-item :label="$t('datasource.database')"
                              prop="database">
                    <el-input v-model="form.database"
                              :placeholder="$t('datasource.placeholder.database')"></el-input>
                </el-form-item>
                <el-form-item :label="$t('datasource.url')" prop="url">
                    <el-input v-model="form.url"
                              :placeholder="$t('datasource.placeholder.url')"></el-input>
                </el-form-item>
                <el-form-item :label="$t('datasource.username')"
                              prop="username">
                    <el-input v-model="form.username"
                              :placeholder="$t('datasource.placeholder.username')"></el-input>
                </el-form-item>
                <el-form-item :label="$t('datasource.password')"
                              prop="password">
                    <el-input v-model="form.password"
                              type="password" autocomplete="new-password"
                              :placeholder="$t('datasource.placeholder.password')"></el-input>
                </el-form-item>
                <el-form-item :label="$t('datasource.tag')" prop="tags">
                    <el-input v-model="form.tags"
                              :placeholder="$t('datasource.placeholder.tag')"></el-input>
                </el-form-item>
                <el-collapse v-model="activeName" accordion>
                    <el-collapse-item :title="$t('datasource.extraInfo')"
                                      name="1">
                        <el-form-item label="Catalog" prop="catalog">
                            <el-input v-model="form.catalog"></el-input>
                        </el-form-item>
                        <el-form-item label="Schema" prop="schema">
                            <el-input v-model="form.schema"></el-input>
                        </el-form-item>
                    </el-collapse-item>
                </el-collapse>
            </el-form>
            <template #footer>
                <div class="fl flex-v">
                    <el-button class="fl" @click="testConnection"
                               :loading="testConnectionLoading">
                        {{ $t('datasource.testConnection') }}
                    </el-button>
                    <span v-if="testConnectionOk===null">
                    </span>
                    <span v-else-if="testConnectionOk===true"
                          style="color: green"
                          class="ml10">
                                连接成功！
                            </span>
                    <el-popover v-else width="300px" placement="top-start"
                                :effect="'dark'">
                        <template #reference>
                            <span style="color: red" class="ml10">
                                连接失败！
                            </span>
                        </template>
                        <span v-if="testConnectionMessage">
                            {{
                            this.testConnectionMessage
                            }}
                        </span>
                        <span v-else>
                            连接失败，请检查连接参数！
                        </span>
                    </el-popover>
                </div>
                <el-button @click="showAddDatasourceDialog=false" type="">
                    {{ $t('button.cancel') }}
                </el-button>
                <el-button @click="addDatasource" type="primary">
                    {{ $t('button.save') }}
                </el-button>
            </template>
        </el-dialog>
        <el-dialog :title="$t('common.detail')"
                   v-model="showDatasourceDetailDialog"
                   width="35vw">
            <el-descriptions column="2">
                <el-descriptions-item label="类型">
                    {{ currDatasource.type }}
                </el-descriptions-item>
                <el-descriptions-item label="名称">
                    {{ currDatasource.name }}
                </el-descriptions-item>
                <el-descriptions-item label="数据库">
                    {{ currDatasource.database }}
                </el-descriptions-item>
                <el-descriptions-item label="描述" span="2">
                    {{ currDatasource.description }}
                </el-descriptions-item>
                <el-descriptions-item label="连接地址" span="2">
                    <span style="word-break:break-all;">
                        {{ currDatasource.url }}
                    </span>
                </el-descriptions-item>
                <el-descriptions-item label="用户名">
                    {{ currDatasource.username }}
                </el-descriptions-item>
                <el-descriptions-item label="密码">
                    ******
                </el-descriptions-item>
                <el-descriptions-item label="驱动文件">
                    {{ currDatasource.driverFile }}
                </el-descriptions-item>
                <el-descriptions-item label="驱动类名">
                    {{ currDatasource.driverClassName }}
                </el-descriptions-item>
                <el-descriptions-item label="创建时间">
                    {{ currDatasource.createDate }}
                </el-descriptions-item>
                <el-descriptions-item label="最近一次同步时间">
                    {{ currDatasource.lastSyncTime }}
                </el-descriptions-item>
            </el-descriptions>
        </el-dialog>

    </div>


</template>
<script>
import api from "@/api/api.js";
import SvgIcon from "@/components/SvgIcon/index.vue";
import SwitchLanguage from "@/views/config/switch-language.vue";

export default {
  name: "my-plugin",
  components: {SwitchLanguage, SvgIcon},
  data() {
    return {
      datasourceTypes: [],
      list: [],
      filterList: [],
      pageInfo: {
        pageSize: 100
      },
      selected: [],
      showDiffDialog: false,
      showAddDatasourceDialog: false,
      showDatasourceDetailDialog: false,
      datasourceDialogTitle: this.$t('datasource.addDatasource'),
      form: {
        name: null,
        catalog: null,
        schema: null,
        database: null,
        url: null,
        type: null,
        description: null,
        username: null,
        password: null,
        tags: null,
        driverFile: null,
        driverClassName: null,
      },
      currDatasource: null,
      rules: {
        type: {required: true, message: '请选择数据源类型'},
        name: {required: true, message: '请填写数据源名称'},
        url: {required: true, message: '请填写连接地址'},
        database: {required: true, message: '请填写数据库名称'},
      },
      filters: {
        name: null,
        tag: []
      },
      language: 'zh-cn',
      testConnectionMessage: null,
      testConnectionOk: null,
      testConnectionLoading: false
    }
  },
  computed: {
    tags() {
      const d = new Set()
      if (this.list) {
        this.list.forEach(v => {
          if (v.tags) {
            const s = v.tags.split(',')
            s.forEach(v => {
              d.add(v)
            })
          }
        })
      }
      return d
    }
  },
  watch: {
    'selected.length': {
      handler(newVal) {
        if (newVal === 2) {
          this.showDiffDialog = true
        }
      },
      deep: true
    },
    filters: {
      handler() {
        this.filter()
      },
      deep: true
    }
  },
  created() {
    this.init()
  },
  methods: {
    init() {
      this.datasourceTypes = api.getDatasourceTypes()
      this.loadData()
    },
    loadData() {
      api.getDatasourceList(this.pageInfo).then(res => {
        const data = res.data.data
        this.list = data.list
        this.filterList = data.list
        this.pageInfo.total = data.total
      })
    },
    select(ds) {
      ds.selected = true
      this.selected.push(ds)
      if (this.selected.length > 2) {
        this.selected[0].selected = false
        this.selected.splice(0, 1)
      }
    },
    cancelSelected(ds) {
      ds.selected = false
      this.selected.splice(this.selected.indexOf(ds), 1)
    },
    cleanSelected() {
      this.filterList.forEach(v => {
        v.selected = false
      })
      this.selected = [];
    },
    goDiff() {
      this.$router.push({
        path: '/diff',
        query: {
          datasourceId1: this.selected[0].id,
          datasourceId2: this.selected[1].id,
        }
      })
    },
    openAddDatasourceDialog() {
      this.form = {
        name: null,
        url: null,
        type: null,
        description: null,
        username: null,
        password: null,
        tags: null
      }
      this.showAddDatasourceDialog = true
      this.$refs['form'].resetFields()
    },
    resetTestConnection() {
      this.testConnectionLoading = false
      this.testConnectionOk = null
      this.testConnectionMessage = null
    },
    addDatasource() {
      this.$refs['form'].validate((success) => {
        if (!success) {
          return
        }
        if (!this.form.id) {
          api.addDatasource(this.form).then(res => {
            const data = res.data
            if (data.code === 0) {
              this.$message.success('添加成功')
              this.loadData()
              this.showAddDatasourceDialog = false
            }
          })
        } else {
          api.updateDatasource(this.form).then(res => {
            const data = res.data
            if (data.code === 0) {
              this.$message.success('修改成功')
              this.loadData()
              this.showAddDatasourceDialog = false
            }
          })
        }

      })
    },
    edit(datasource) {
      this.form = {...datasource}
      this.datasourceDialogTitle = this.$t('datasource.updateDatasource')
      this.showAddDatasourceDialog = true
    },
    showDatasourceDetail(ds) {
      this.showDatasourceDetailDialog = true
      this.currDatasource = ds
    },
    remove(ds) {
      this.$confirm('确定删除数据源：' + ds.name).then(() => {
        api.deleteDatasource({
          id: ds.id
        }).then(res => {
          const data = res.data
          if (data.code === 0) {
            this.loadData()
            this.$message.success('删除成功')
          }
        })
      })
    },
    sync(ds) {
      ds.syncing = true
      api.sync({
        datasourceId: ds.id
      }).then(res => {
        const data = res.data
        if (data.code === 0) {
          this.loadData()
          ds.syncing = false
          this.$message.success('同步成功')
        } else {
          ds.syncing = false
          this.$message.error(data.msg)
        }
      })
    },
    filter() {
      this.filterList = this.list.filter(v => {
        let b = true
        if (this.filters.name) {
          if (!v.name) {
            b = false
          } else {
            b = b && v.name.indexOf(this.filters.name) > -1 || v.database.indexOf(this.filters.name) > -1
          }
        }
        if (this.filters.tag && this.filters.tag.length > 0) {
          if (!v.tags) {
            b = false
          } else {
            b = b && v.tags.split(',').filter(item => this.filters.tag.includes(item)).length > 0
          }
        }
        return b
      })
    },
    testConnection() {
      this.resetTestConnection()
      this.testConnectionLoading = true
      api.testConnection({
        type: this.form.type,
        url: this.form.url,
        username: this.form.username,
        password: this.form.password
      }).then(res => {
        this.testConnectionLoading = false
        const data = res.data
        if (data.code === 0) {
          this.testConnectionOk = true
          this.testConnectionMessage = '连接成功'
        } else {
          this.testConnectionOk = false
          this.testConnectionMessage = data.msg
        }
      })
    }
  }
}
</script>
<style scoped>
:deep(.el-button.is-text) {
    padding: 0;
}

:deep(.el-descriptions__label) {
    width: 80px;
}

.selected-parent {
    position: relative;

    .selected {
        border-radius: 5px;
        width: 100%;
        height: 251px;
        background: rgba(67, 67, 80, 0.5);
        margin-top: -251px;

        .el-button {
            margin-top: 100px;
        }
    }
}

.connection-notify {
    width: 500px;
}

</style>
